﻿using System;
using System.IO;

namespace OpenWaves
{
    public static class StreamExtensions
    {
        public static Stream Append(this Stream destination, Stream source)
        {
            var buffer = new byte[BinaryUnit.FromKilobytes(16)];
            while (true)
            {
                int read = source.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                    return destination;
                destination.Write(buffer, 0, read);
            }
        }

        public static Stream Append(this Stream destination, Stream source, long maxLength)
        {
            var buffer = new byte[BinaryUnit.FromKilobytes(16)];

            long bytesLeftToRead = maxLength;
            while (true)
            {
                int read = source.Read(buffer, 0, (int)Math.Min(buffer.Length, bytesLeftToRead));
                if (read <= 0)
                    return destination;
                bytesLeftToRead -= read;
                destination.Write(buffer, 0, read);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        public static MemoryStream CopyToMemoryStream(this Stream input)
        {
            var copy = input.CanSeek ? new MemoryStream((int)input.Length) : new MemoryStream();
            copy.Append(input).Seek(0, SeekOrigin.Begin);
            return copy;
        }
    }
}